package org.jeecg.modules.system.service.impl;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.modules.system.entity.CommonUsedApp;
import org.jeecg.modules.system.mapper.CommonUsedAppMapper;
import org.jeecg.modules.system.service.ICommonUsedAppService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @Description: 用户常用表
 * @Author: jeecg-boot
 * @Date: 2024-07-15
 * @Version: V1.0
 */
@Service
public class CommonUsedAppServiceImpl extends ServiceImpl<CommonUsedAppMapper, CommonUsedApp> implements ICommonUsedAppService {
    @Resource
    private CommonUsedAppMapper commonUsedAppMapper;

    @Override
    public int addApp(JSONArray jsonArray) {

        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        LambdaQueryWrapper<CommonUsedApp> queryWrapper = new LambdaQueryWrapper<CommonUsedApp>()
                .eq(CommonUsedApp::getUserId, user.getId());
        List<CommonUsedApp> commonUsedAppList = new ArrayList<>();
        commonUsedAppMapper.delete(queryWrapper);
        if (jsonArray.size() != 0) {
            jsonArray.forEach(jsonElement -> {
                CommonUsedApp commonUsedApp = CommonUsedApp.buildCommonUsedApp((JSONObject) jsonElement, user);
                commonUsedAppList.add(commonUsedApp);
            });
            this.saveBatch(commonUsedAppList);
        }
        return 1;
    }


}
